package com.universest.swordholder.ui.screen

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalWindowInfo
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.universest.swordholder.aitool.Message
import com.universest.swordholder.viewmodel.ChatScreenViewModel
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
import androidx.compose.material.icons.automirrored.filled.Send
import androidx.compose.material.icons.filled.AddComment
import androidx.compose.material.icons.filled.ExpandMore
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.TextField
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.sp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.universest.swordholder.R
import dev.jeziellago.compose.markdowntext.MarkdownText
import kotlin.math.roundToInt

@Composable
fun ChatBubbleList(
    messages: List<Message>,
    modifier: Modifier = Modifier,
    viewModel: ChatScreenViewModel
) {
    val windowInfo = LocalWindowInfo.current
    val screenWidth = windowInfo.containerSize.width

    // 计算最大宽度为屏幕宽度的80%
    val maxBubbleWidth = with(LocalDensity.current){(screenWidth * 0.8f).toDp()}

    LazyColumn(
        modifier = modifier,
        reverseLayout = true // 让最新消息在底部
    ) {
        itemsIndexed(messages.asReversed()) { index,message ->
            ChatBubbleItem(
                message = message,
                maxWidth = maxBubbleWidth,
                modifier = Modifier.fillMaxWidth().alpha(0.9f),
                viewModel = viewModel,
                isLastMessage = index == 0
            )
        }
    }
}

@Composable
fun ChatBubbleItem(
    message: Message,
    maxWidth: Dp,
    modifier: Modifier = Modifier,viewModel: ChatScreenViewModel,
    isLastMessage: Boolean = false
) {
    // 根据消息发送者决定对齐方式
    val alignment = if (message.isMe) Alignment.CenterEnd else Alignment.CenterStart
    val bubbleColor = if (message.isMe) {
        MaterialTheme.colorScheme.primary
    } else {
        MaterialTheme.colorScheme.surfaceVariant
    }
    val contentColor = if (message.isMe) {
        MaterialTheme.colorScheme.onPrimary
    } else {
        MaterialTheme.colorScheme.onSurfaceVariant
    }

    Box(
        modifier = modifier,
        contentAlignment = alignment
    ) {
        Box(
            modifier = Modifier
                .widthIn(max = maxWidth)
                .padding(horizontal = 16.dp, vertical = 4.dp)
        ) {
            // 聊天气泡背景
            Box(
                modifier = Modifier
                    .clip(RoundedCornerShape(16.dp))
                    .background(bubbleColor)
                    .padding(horizontal = 12.dp, vertical = 8.dp)
            ) {

                Column(modifier = Modifier.wrapContentWidth()) {
                    var expandDeepThought by remember { mutableStateOf(true) }
                    val deepThinking by viewModel.deepThinking.collectAsStateWithLifecycle()
                    if(message.deepThought.isNotEmpty()){
                        Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.clickable(onClick = {
                            expandDeepThought = !expandDeepThought
                        })) {
                            IconButton(
                                modifier = Modifier.size(24.dp),
                                onClick =  {
                                expandDeepThought = !expandDeepThought
                            }) {
                                Icon(
                                    modifier = Modifier.fillMaxSize(),
                                    imageVector = if(expandDeepThought) Icons.Default.ExpandMore else Icons.AutoMirrored.Filled.KeyboardArrowRight,
                                    contentDescription = null,
                                    tint = contentColor,
                                )
                            }
                            val shouldBlink = deepThinking && isLastMessage
                            // 创建无限动画容器
                            val infiniteTransition = rememberInfiniteTransition(label = "deepThoughtBlinkTransition")
                            val blinkAlpha: Float by (
                                if (shouldBlink) {
                                    infiniteTransition.animateFloat(
                                        initialValue = 0.3f,
                                        targetValue = 1f,
                                        animationSpec = infiniteRepeatable(
                                            animation = tween(durationMillis = 500),
                                            repeatMode = RepeatMode.Reverse
                                        ),
                                        label = "deepThoughtBlink"
                                    )
                                } else {
                                    remember { mutableFloatStateOf(1f) }
                                }
                            )

                            val displayDots = ".".repeat((blinkAlpha * 6).roundToInt())
                            val displayAlpha = if (shouldBlink) blinkAlpha else 1f
                            Text(
                                text = if(shouldBlink) {
                                    "深度思考中$displayDots"
                                } else {"深度思考"},
                                color = contentColor.copy(alpha = displayAlpha),
                                style = MaterialTheme.typography.bodySmall,
                                modifier = Modifier
                                    .weight(1f),
                                textAlign = if (message.isMe) TextAlign.End else TextAlign.Start
                            )
                        }
                        AnimatedVisibility(visible = expandDeepThought,
                            enter = slideInVertically { it },
                            exit = slideOutVertically { it },
                            modifier = Modifier
                                .wrapContentWidth()
                                .clipToBounds()) {
                            Text(
                                text = message.deepThought,
                                color = contentColor.copy(alpha = 0.5f),
                                style = MaterialTheme.typography.bodySmall,
                                modifier = Modifier.wrapContentWidth(),
                                textAlign = if (message.isMe) TextAlign.End else TextAlign.Start
                            )
                        }
                        HorizontalDivider(modifier = Modifier.padding(vertical = 4.dp), color = contentColor.copy(alpha = 0.5f))
                    }
                    val receiving by viewModel.receiving.collectAsStateWithLifecycle()
                    val contentBlink = isLastMessage && message.role == "assistant" && receiving && message.content.isEmpty()
                    val infiniteTransition = rememberInfiniteTransition(label = "contentBlinkTransition")
                    val blinkAlpha by if(contentBlink)infiniteTransition.animateFloat(
                        initialValue = 0.3f,
                        targetValue = 1f,
                        animationSpec = infiniteRepeatable(
                            animation = tween(durationMillis = 500),
                            repeatMode = RepeatMode.Reverse
                        ),
                        label = "contentBlink"
                    )else {
                        remember { mutableFloatStateOf(1f) }
                    }
                    val displayAlpha = if (contentBlink) blinkAlpha else 1f
                    MarkdownText(
                        isTextSelectable = true,
                        markdown = if(contentBlink) "正在思考${".".repeat((blinkAlpha * 6).roundToInt())}" else {message.content},
                        style = MaterialTheme.typography.bodyMedium.copy(
                            fontSize = 16.sp,
                            lineHeight = 22.sp,
                            color = contentColor.copy(alpha = displayAlpha)),
                        modifier = Modifier.wrapContentWidth()
                        //textAlign = if (message.isMe) TextAlign.End else TextAlign.Start
                    )
                }
            }
        }
    }
}

val Message.isMe
    get() = role == "user"

@Composable
fun ChatScreen(modifier: Modifier, viewModel: ChatScreenViewModel = viewModel()) {
    var inputText by remember { mutableStateOf("") }
    val messages = viewModel.messages
    val receiving by viewModel.receiving.collectAsStateWithLifecycle()
    val resetEnable = !receiving && messages.isNotEmpty()
    Column(modifier = modifier) {
        // 修改 ChatScreen 中的标题栏部分
        Box(modifier = Modifier
            .fillMaxWidth()
            .height(60.dp)) {
            Text(
                "小捉",
                fontSize = 20.sp,
                color = MaterialTheme.colorScheme.onSurface,
                modifier = Modifier.align(Alignment.Center)
            )

            IconButton(
                enabled = resetEnable,
                onClick = {
                    viewModel.resetMessages()
                },
                modifier = Modifier.align(Alignment.CenterEnd)
            ) {
                Icon(
                    tint = MaterialTheme.colorScheme.onSurface.copy(alpha = if(resetEnable)1f else 0.5f),
                    imageVector = Icons.Filled.AddComment,
                    contentDescription = "创建新对话"
                )
            }
        }
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .weight(1f)
        ) {
            Image(
                painter = painterResource(id = R.drawable.sword_holder),
                contentDescription = null,
                contentScale = ContentScale.Crop,
                modifier = Modifier
                    .fillMaxSize()
                    .clipToBounds()
            )

            // 组合的渐变遮罩 - 顶部和底部同时渐变
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .background(
                        brush = Brush.verticalGradient(
                            colors = listOf(
                                MaterialTheme.colorScheme.background,        // 顶部不透明
                                Color.Transparent,  // 中间透明
                                Color.Transparent,  // 中间透明
                                MaterialTheme.colorScheme.background         // 底部不透明
                            ),
                            startY = 0f,
                            endY = Float.POSITIVE_INFINITY
                        )
                    )
            )
            ChatBubbleList(
                messages = messages,
                modifier = Modifier
                    .fillMaxWidth(),
                viewModel = viewModel
            )
        }
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(8.dp)
                .wrapContentHeight(),
            verticalAlignment = Alignment.CenterVertically
        ) {
            val receiving by viewModel.receiving.collectAsStateWithLifecycle()
            TextField(
                enabled = !receiving,
                value = inputText,
                onValueChange = { inputText = it },
                modifier = Modifier
                    .fillMaxWidth()
                    .heightIn(min = 60.dp, max = 240.dp)
                    .weight(1f),
                placeholder = { Text("输入消息...") }
            )
            val enabled = inputText.isNotBlank() && !receiving
            IconButton(
                enabled = enabled,
                onClick = {
                    if (inputText.isNotBlank()) {
                        viewModel.sendMessage(inputText)
                        inputText = ""
                    }
                }
            ) {
                Icon(
                    tint = if(enabled)MaterialTheme.colorScheme.onSurface else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.5f),
                    imageVector = Icons.AutoMirrored.Filled.Send,
                    contentDescription = "发送"
                )
            }
        }
    }
}


// 使用示例
@Composable
@Preview
fun ChatScreenPreview() {
    
}